package lx.scrmXj;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import lx.scrmXj.pojo.ParentId;
import lx.util.DateUtil;
import lx.util.HttpHelper;
import lx.util.StrUtil;

import java.text.MessageFormat;
import java.util.Date;
import java.util.List;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;

/**
 * @Description: 成员信息同步
 * @Author: 李星 lixing_java@163.com
 * @Date: 2020/3/13 22:11
 */
public class UserTask extends TimerTask {

    @Override
    public void run() {
        try {
            // 查询本地部门信息列表
            List<Record> departmentList = Db.find("SELECT ID,PARENTID,NAME FROM XJ_SCRM_DEPARTMENT ORDER BY CREATE_TIME DESC");
            int departmentCount = departmentList.size();
            System.out.println(MessageFormat.format("{0} 本地部门数量：{1}", DateUtil.dateToDateTimeCharacter(new Date()), departmentCount));
            //
            ExecutorService executorService = Executors.newFixedThreadPool(20);
            IntStream.range(0, departmentCount).forEach(i -> {
                executorService.submit(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            userTask(departmentList.get(i), i);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
            });
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println();
        }
    }

    // 查询通讯录token
    public String getToken() throws Exception {
        String tokenUrl = "SELECT ACCESS_TOKEN FROM XJ_SCRM_TOKEN where CATEGORY = 1 ORDER BY CREATE_TIME DESC";
        List<Record> recordTokenList = Db.find(tokenUrl);
        String token = recordTokenList.get(0).getStr("ACCESS_TOKEN");
//        System.out.println(MessageFormat.format("{0} 成员信息同步获取token：{1}", DateUtil.dateToDateTimeCharacter(new Date()), token));
        return token;
    }

    // 根据部门编号获取部门的绝对路径
    public JSONObject getUserAllDepartment(int departmentId) {
        JSONObject departmentInfo = new JSONObject();
        StringBuilder departmentIdStr = new StringBuilder();
        StringBuilder departmentNameStr = new StringBuilder();
        String parentInfo = ParentId.getParentDepartmentInfo(departmentId); // TODO 递归获取当前部门的所有上级部门信息，返回格式：编号|名称;编号|名称;编号|名称;
        String[] parentInfos = parentInfo.split(";"); // [ 编号|名称, 编号|名称, 编号|名称, 编号|名称 ]
        for (int i = 0; i < parentInfos.length; i++) {
            String[] parentInfos_ = parentInfos[i].split("\\|");
            departmentIdStr.append(parentInfos_[0]);
            departmentNameStr.append(parentInfos_[1]);
            if (i != parentInfos.length - 1) {
                departmentIdStr.append("/");
                departmentNameStr.append("/");
            }
        }
        departmentIdStr.append(",");
        departmentNameStr.append(",");
        //
        departmentInfo.put("departmentIdStr", departmentIdStr); // 数据格式：编号/编号/编号/编号
        departmentInfo.put("departmentNameStr", departmentNameStr); // 数据格式： 名称/名称/名称/名称
        return departmentInfo;
    }

    // 根据部门编号，查询其所有成员信息
    public void userTask(Record departmentRecord, int index) throws Exception {
        int departmentId = departmentRecord.getInt("ID"); // TODO ----------------------------------当前部门编号
        String departmentName = departmentRecord.getStr("NAME"); // TODO ---------------------------当前部门名称
        try {
            // TODO 根据部门编号，查询其所有成员信息。fetch_child 是否递归获取子部门下面的成员，0否 1是
            String userRes = HttpHelper.sendRequestHttps(
                    "https://qyapi.weixin.qq.com/cgi-bin/user/list?access_token=" + getToken() + "&department_id=" + departmentId + "&fetch_child=0",
                    "GET",
                    null);
            JSONObject userJson = JSON.parseObject(userRes);
            if (0 == userJson.getIntValue("errcode") && "ok".equals(userJson.getString("errmsg"))) {
                JSONArray userArray = userJson.getJSONArray("userlist");
                //
                if (!userArray.isEmpty()) {
                    int userCount = userArray.size();
                    for (int i = 0; i < userCount; i++) {
                        JSONObject userJsonTemp = userArray.getJSONObject(i); // TODO 遍历后的每一个成员信息
                        userJsonTemp.put("order", userJsonTemp.getString("order").replace("[", "").replace("]", ""));
                        userJsonTemp.put("is_leader_in_dept", userJsonTemp.getString("is_leader_in_dept").replace("[", "").replace("]", ""));
                        // 企业微信api返回的部门id编号。数据格式：[1,11,111]
                        String department = userJsonTemp.getString("department").replace("[", "").replace("]", "").replace("，", ",");
                        /*
                         * @Description TODO 解析当前成员的部门信息
                         */
                        StringBuilder departmentIdStr = new StringBuilder();
                        StringBuilder departmentNameStr = new StringBuilder();
                        String[] departmentArray = StrUtil.isEffective(department) ? department.split(",") : null;   // 对部门id编号进行拆分
                        if (departmentArray != null && departmentArray.length > 0) {
                            for (String s : departmentArray) {
                                JSONObject userAllDepartment = getUserAllDepartment(Integer.parseInt(s));
                                departmentIdStr.append(userAllDepartment.getString("departmentIdStr"));
                                departmentNameStr.append(userAllDepartment.getString("departmentNameStr"));
                            }
                            userJsonTemp.put("department_id", departmentIdStr.toString());
                            userJsonTemp.put("department", departmentNameStr.toString());
                        }
                        /*
                         * @Description TODO 与本地进行数据同步
                         */
                        Record record = new Record();
                        record.set("GENDER", userJsonTemp.getIntValue("gender"));
                        record.set("ISLEADER", userJsonTemp.getIntValue("isleader"));
                        record.set("ENABLE", userJsonTemp.getIntValue("enable"));
                        record.set("STATUS", userJsonTemp.getIntValue("status"));
                        record.set("HIDE_MOBILE", userJsonTemp.getIntValue("hide_mobile")); // 是否隐藏手机号
                        record.set("USERID", userJsonTemp.getString("userid").trim());
                        record.set("NAME", userJsonTemp.getString("name"));
                        record.set("ENGLISH_NAME", userJsonTemp.getString("english_name"));
                        record.set("ALIAS", userJsonTemp.getString("alias"));
                        record.set("MOBILE", userJsonTemp.getString("mobile"));
                        record.set("DEPARTMENT", userJsonTemp.getString("department"));
                        record.set("DEPARTMENT_ID", userJsonTemp.getString("department_id")); // 自定义，与api返回的数据结构无关
                        record.set("\"ORDER\"", userJsonTemp.getString("order"));
                        record.set("POSITION", userJsonTemp.getString("position"));
                        record.set("EMAIL", userJsonTemp.getString("email"));
                        record.set("TELEPHONE", userJsonTemp.getString("telephone"));
                        record.set("AVATAR_MEDIAID", userJsonTemp.getString("avatar_mediaid"));
                        record.set("IS_LEADER_IN_DEPT", userJsonTemp.getString("is_leader_in_dept"));
                        record.set("AVATAR", userJsonTemp.getString("avatar"));
                        record.set("THUMB_AVATAR", userJsonTemp.getString("thumb_avatar"));
                        record.set("QR_CODE", userJsonTemp.getString("qr_code"));
                        record.set("ADDRESS", userJsonTemp.getString("address"));
                        record.set("TO_INVITE", userJsonTemp.getString("to_invite"));
                        record.set("OPEN_USERID", userJsonTemp.getString("open_userid")); // TODO 全局唯一。对于同一个服务商，不同应用获取到企业内同一个成员的open_userid是相同的
                        record.set("EXTERNAL_POSITION", userJsonTemp.getString("external_position"));
                        record.set("EXTERNAL_PROFILE", userJsonTemp.getString("external_profile")); // TODO 成员对外属性，不做任何处理存入数据库
                        record.set("EXTATTR", userJsonTemp.getString("extattr")); // TODO 扩展属性，第三方仅通讯录应用可获取，不做任何处理存入数据库
                        //
                        Record userInfo = Db.findFirst("SELECT USERID FROM XJ_SCRM_USER WHERE USERID = ?", record.getStr("USERID"));
                        String operateFlag;
                        boolean resultFlag = true;
                        if (userInfo == null) {
                            // TODO 发起添加
                            operateFlag = "insert";
                            resultFlag = Db.save("XJ_SCRM_USER", "userid", record);
                        } else {
                            // TODO 发起更新
                            operateFlag = "update";
                            //resultFlag = Db.update("XJ_SCRM_USER", "userid", record); // 如果是迭代递增的需求，则次处开启
                        }
                        System.out.println(MessageFormat.format("{0} 第{1}条 部门（{2}--{3}）{4}成员（{5}）结果：{6}",
                            DateUtil.dateToDateTimeCharacter(new Date()), index, departmentId, departmentName, operateFlag, record.getStr("USERID"), resultFlag));
                        System.out.println();
                    }
                }
            } else {
                System.out.println(MessageFormat.format("{0} 第{1}条 获取部门（{2}--{3}）的成员 失败：{4}",
                        DateUtil.dateToDateTimeCharacter(new Date()), index, departmentId, departmentName, userRes));
            }
        } catch (Exception e) {
            System.out.println(MessageFormat.format("{0} 第{1}条 获取部门（{2}--{3}）的成员 出错：{4}",
                    DateUtil.dateToDateTimeCharacter(new Date()), index, departmentId, departmentName, e.getMessage()));
        }
    }

}
